<template>
  <!-- 增加投资人模块后关闭返回按钮，起始页面就是登录页 -->
  <!-- <Nav_bar :title="nav_bar_title" class="Nav_bar" /> -->
  <div class="login_box">
    <img class="login_img" src="/src/assets/logo/logo.png" alt="" />
    <form class="_form">
      <div class="form_phone">
        <text class="icon phone"></text>
        <input
          class="phone_input"
          type="text"
          v-model.trim="loginForm.phone"
          placeholder="请输入您的手机号码"
          maxlength="11"
        />
      </div>
      <div class="form_lock" v-if="loginType">
        <text class="icon lock"></text>
        <input
          class="lock_input"
          v-model.trim="loginForm.paw"
          type="password"
          autocomplete="new-password"
          placeholder="请输入密码"
          maxlength="16"
          minlength="4"
        />
      </div>
      <div class="form_lock" v-else>
        <text class="icon lock"></text>
        <input
          class="lock_input"
          v-model.trim="loginForm.code"
          type="text"
          placeholder="请输入验证码"
          maxlength="4"
        />
        <button
          class="_code"
          type="button"
          :disabled="isDisabled"
          @click.stop="getPhoneCode()"
          :style="{
            color: isCodeStyle ? '' : '#A8A8A8',
          }"
        >
          {{ btnText }}
        </button>
      </div>

      <div class="user_agreement">
        <van-checkbox
          class="_checkbox"
          v-model="_checked"
          checked-color="#15C691"
          :icon-size="12"
        ></van-checkbox>
        <div class="user_agreement_text">
          <span @click.stop="_checked = !_checked">我已阅读并同意</span>
          <div @click.stop="$router.push('/agreement')" class="agreement">
            《杭州约饭派科技有限公司用户协议》
          </div>
        </div>
      </div>
      <div class="huanHang">
        及 <span @click.stop="$router.push('/privacy')" class="agreement">《隐私协议》</span>
      </div>

      <van-button
        type="primary"
        round
        size="normal"
        color="linear-gradient(to right, #66dfbc, #14c691)"
        :disabled="!disabled"
        :loading="loading"
        :block="true"
        @click="login()"
      >
        登录
      </van-button>
    </form>
    <div class="skip_editPaw" @click="skip_changePaw()">忘记密码</div>
  </div>
  <van-action-sheet
    v-model:show="show"
    :actions="actions"
    cancel-text="取消"
    close-on-click-action
    @select="select"
  />
</template>

<script setup>
import { ref, onMounted, computed, onUpdated } from 'vue'
import { useCountButton } from '@/hooks/common'
import { Msg } from '@/utils/tools'
import {
  postCodeLoginApi,
  postPawLoginApi,
  postPhoneCodeApi,
  getVisitorIdApi,
  getUserInfoApi,
} from '@/api/user/user'
import { encryption } from '@/utils/rsa_encipher'
import { useRouter, useRoute } from 'vue-router'
import FingerprintJS from '@fingerprintjs/fingerprintjs'
import { useUserInfoStore, usePhoneInfoStore } from '@/stores'
import { UERR_RIGHTS } from '@/utils/enums'

const userInfoStore = useUserInfoStore()
const phoneInfoStore = usePhoneInfoStore()
const { btnText, disabled: isDisabled, startCount } = useCountButton()
const nav_bar_title = ref('账号登录')
const loginForm = ref({ phone: phoneInfoStore.phone || '', code: '', paw: '' })
const _checked = ref(false)
const disabled = ref(false)
const loginType = ref(true)
const $router = useRouter()
const loading = ref(false)
const visitorId = ref()
const userInfo = ref({
  nickName: null,
  userId: null,
  userType: null,
})
const show = ref(false)
const actions = [
  { value: 'customerService', name: '客服' },
  { value: 'investor', name: '创客' },
]

/** 判断用户是否第一次登录 */
const getVisitorId = async () => {
  const res = await getVisitorIdApi({ token: visitorId.value })
  console.log(res)
  loginType.value = res.data === 1 ? true : false
}

/** 点击登录 */
const login = async () => {
  if (!_checked.value) return Msg('请同意用户协议')
  loading.value = true
  phoneInfoStore.setPhone(loginForm.value.phone)
  let result
  if (loginType.value) {
    // 调用密码接口
    result = await postPawLoginApi({
      phone: loginForm.value.phone,
      password: encryption(loginForm.value.paw),
    }).catch(() => {
      loading.value = false
    })
  } else {
    // 调用验证码接口
    result = await postCodeLoginApi({
      phone: loginForm.value.phone,
      captcha: loginForm.value.code,
      visitorId: visitorId.value,
    }).catch(() => {
      loading.value = false
    })
  }
  userInfoStore.setToken(result.data?.access_token)
  getUserInfo()
}

/** 获取用户信息 */
const getUserInfo = async () => {
  const res = await getUserInfoApi().finally(() => {
    loading.value = false
  })
  console.log(res.data)
  processingUserData(res.data)
}

/**处理返回的用户数据,并且保存到本地 */
const processingUserData = (data) => {
  phoneInfoStore.setPhone(data.userName) // 单独缓存
  userInfo.value.nickName = data.nickName
  userInfo.value.userId = data.userId
  const typeList = []
  /**检查 role 是否符合 isInvestor 条件 */
  function isInvestorRole(role) {
    return [
      'investor',
      'specialMerchants',
      'ordinaryMerchants',
      'Individual',
      'investorManager',
    ].includes(role.roleKey)
  }

  /**检查 role 是否符合 isPostionCustomer 条件 */
  function isPostionCustomerRole(role) {
    return role.roleKey.includes('postionCustomer') || role.roleKey === 'customerService'
  }

  /**检查 typeList 中是否存在某个角色 */
  function hasRole(typeList, role) {
    return typeList.some((r) => r.roleKey === role.roleKey)
  }
  data.roles.forEach((item) => {
    if (typeList.length < 2) {
      const isPostionCustomer = typeList.some(isPostionCustomerRole)
      const isInvestor = typeList.some(isInvestorRole)
      if (!isPostionCustomer && isPostionCustomerRole(item) && !hasRole(typeList, item)) {
        typeList.push(item)
      } else if (!isInvestor && isInvestorRole(item) && !hasRole(typeList, item)) {
        typeList.push(item)
      }
    }
  })
  console.log(typeList)
  if (typeList.length === 1) {
    console.log(typeList[0].roleKey)
    userInfo.value.userType =
      typeList[0].roleKey.includes('postionCustomer') || typeList[0].roleKey === 'customerService'
        ? 'customerService'
        : 'investor'
    userInfoStore.setUserInfo(userInfo.value)
    typeList[0].roleKey.includes('investor')
      ? $router.push('/ivestorMachine')
      : $router.push('/machine')
  } else {
    show.value = true // 开启下拉抽屉
  }
}

/**获取下拉抽屉选中的用户权限 */
const select = (ev) => {
  userInfo.value.userType = ev.value
  userInfoStore.setUserInfo(userInfo.value)
  ev.value.includes('investor') ? $router.push('/ivestorMachine') : $router.push('/machine')
}

onUpdated(() => {
  disabled.value =
    (loginForm.value.phone.length >= 11 && loginForm.value.code.length >= 4) ||
    (loginForm.value.phone.length >= 11 &&
      loginForm.value.paw.length <= 16 &&
      loginForm.value.paw.length >= 6)
      ? true
      : false
})
/** 获取验证码 */
const getPhoneCode = async () => {
  // 正则校验
  let reg = /^1[3-9]\d{9}$/
  if (!reg.test(loginForm.value.phone)) {
    return Msg('请输入正确的手机号')
  }
  const res = await postPhoneCodeApi({ phone: loginForm.value.phone, type: 1 })
  if (res.code === 200) {
    startCount()
    Msg('验证码已发送')
  }
}
/** 判断验证码样式 */
const isCodeStyle = computed(() => {
  return loginForm.value.phone.length >= 11 && btnText.value === '获取验证码' ? true : false
})
/**跳转修改密码页 */
const skip_changePaw = () => {
  $router.push('/change_paw')
}
onMounted(() => {
  /**获取浏览器的唯一id */
  if (!sessionStorage.getItem('flag')) {
    $router.go(0)
    sessionStorage.setItem('flag', true)
  }
  FingerprintJS.load().then((fp) => {
    fp.get().then((result) => {
      visitorId.value = result.visitorId
      getVisitorId()
    })
  })
})
</script>

<style lang="scss" scoped>
.Nav_bar {
  background: #effaf6;
  :deep(.van-nav-bar__title) {
    color: #000;
  }
  :deep(.van-icon) {
    color: #000;
  }
}
.login_box {
  width: 100%;
  height: 100%;
  padding-top: 44px;
  background: linear-gradient(to top, #fff, #eaf9f4);
  display: flex;
  flex-direction: column;
  align-items: center;
}
.login_img {
  width: 152px;
  height: 152px;
  border-radius: 8px;
  margin: 51px 0 29px 0;
}
._form {
  .form_phone,
  .form_lock {
    width: 299px;
    height: 44px;
    border-radius: 4px;
    background: #fff;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    font-size: 12px;
    .phone {
      font-size: 22px;
      color: #09d336;
      margin: 0 5px 0 3px;
    }
    .lock {
      font-size: 16px;
      color: #09d336;
      margin: 0 8px 0 6px;
    }
    .phone_input,
    .lock_input {
      flex: 1;
    }
    ._code {
      color: #06cd93;
      border-left: 1px solid #a8a8a8;
      padding: 0 7px 0 9px;
      background-color: transparent;
    }
  }
}
.user_agreement {
  width: 100%;
  height: 20px;
  display: flex;
  align-items: center;
  color: var(--c9);

  ._checkbox {
    width: 15px;
  }
  .user_agreement_text {
    display: flex;
    width: 100%;
    font-size: var(--fs10);
    margin-left: 4px;
    .agreement {
      color: #15c691;
    }
  }
}
.huanHang {
  font-size: var(--fs10);
  color: var(--c9);
  margin: 0 0 39px 18px;
  .agreement {
    color: #15c691;
  }
}
.skip_editPaw {
  width: 299px;
  color: #a8a8a8;
  font-size: 12px;
  text-align: right;
  margin-top: 32px;
}
</style>
